<template>
  <view :data-theme="theme">
    <view class="cart_nav" style="height: 20rpx;">
      <!-- #ifndef APP-PLUS -->
      <nav-bar 
        iconColor="#fff" 
        ref="navBarRef" 
        :isBackgroundColor="false" 
        navTitle="开票记录"
        :leftBtn="{
          icon: 'icon-fanhui', 
          text: '返回', 
          onClick: () => this.goBack()
        }"
        :rightBtn="{
          icon: 'icon-shouye', 
          text: '首页', 
          onClick: () => this.goHome()
        }"
      >
      </nav-bar>
      <!-- #endif -->
    </view>

    <!-- 数据展示区域 -->
    <view class="data-list">
      <view 
        v-for="(item, index) in invoiceList" 
        :key="index" 
        class="car-item"
        :class="{ active: selectedInvoiceIndex === index }"
        @click="handleInvoiceClick(item, index)"
        v-if="index < pageSize * currentPage && index >= pageSize * (currentPage - 1)"
      >
        <!-- <image class="icon" src="../../../static/tabBar/invoice.png"></image> -->
        <view class="invoice-info">
          <text class="invoice-date">{{ formatDate(item.createTime) }}  停车费 {{item.totalAmount}}元</text>
        </view>
        <button @click.stop="issueInvoice(index)" class="issue-button">开 票</button>
      </view>

      <!-- 加载更多提示 -->
      <!-- <view v-if="!isLoading && hasMore" class="load-more" @click="loadMore">
        加载更多
      </view>
      <view v-if="isLoading" class="loading">
        <text>加载中...</text>
      </view>
      <view v-if="!hasMore && invoiceList.length > 0" class="no-more">
        没有更多数据了
      </view> -->

      <!-- 提示信息 -->
      <view class="hint-text" v-show="invoiceList.length === 0">暂无开票记录</view>
    </view>

    <!-- 分页组件 -->
    <view class="pagination-container">
      <uni-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalCount"
        @change="handlePaginationChange"
        background-color="#FE725C"
        text-color="#fff"
        :border-radius="40"
        mode="buttons"
      />
    </view>

    <!-- 弹窗：开票确认 -->
    <uni-popup ref="invoicePopup" :mask-click="false">
      <view class="popup-content rounded-box">
        <text>确定要为该订单开票吗？</text>
        
        <!-- 订单信息 -->
        <view class="invoice-detail">
          <view class="detail-item">
            <text class="detail-label">金额：</text>
            <text class="detail-value">{{ selectedInvoice.totalAmount }}元</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="popup-buttons">
          <button class="popup-button cancel" @click="cancelIssueInvoice">取消</button>
          <button class="popup-button confirm" @click="confirmIssueInvoice">确认开票</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { invoiceDaikai, invoiceIssue } from '@/api/parking.js';
export default {
  data() {
    return {
      theme: 'default',
      navH: 100,
      invoiceList: [],
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      totalCount: 0,
      isLoading: false,
      hasMore: true,
      selectedInvoiceIndex: null,
      selectedInvoice: null,
      plateNumber: Array(8).fill(''),
      currentInput: 0,
      keyboardVisible: false,
      keyboardType: 1,
      isNewEnergy: false,
      zIndex: {
        keyboard: 1000,
        popup: 999,
      }
    };
  },

  onLoad() {
    this.getInvoiceList();
  },
  
  onReachBottom() {
    this.loadMore();
  },

  methods: {
    handleInvoiceClick(item, index) {
      this.selectedInvoiceIndex = index;
      this.selectedInvoice = item;
    },

    getInvoiceList(pageNum = 1, isRefresh = false) {
      if (isRefresh) {
        this.currentPage = pageNum;
      } else if (!this.hasMore) {
        return;
      }
      
      this.isLoading = true;
      
      const openid = uni.getStorageSync('openid');
      if (openid) {
        let params = {
          openid: openid,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        
        invoiceDaikai(params)
          .then(res => {
            const data = res || {};
            const list = data.records || data.rows || [];
            this.totalCount = data.total || data.count || 0;
            this.totalPages = Math.ceil(this.totalCount / this.pageSize);

            console.log('获取开票记录:', list);
            console.log('获取开票记录totalPages:', this.totalPages );

            this.hasMore = this.currentPage < this.totalPages;
            
            if (isRefresh) {
              this.invoiceList = list;
            } else {
              this.invoiceList = [...this.invoiceList, ...list];
            }
          })
          .catch(err => {
            console.error('获取开票记录失败:', err);
            uni.showToast({
              title: '获取开票记录失败',
              icon: 'none'
            });
          })
          .finally(() => {
            this.isLoading = false;
          });
      } else {
        console.error('未获取到openid');
        uni.showToast({
          title: '未获取到openid，请重新登录',
          icon: 'none'
        });
        this.isLoading = false;
      }
    },
    
    refreshInvoiceList() {
      uni.showLoading({ title: '刷新中...' });
      this.getInvoiceList(1, true);
      uni.hideLoading();
    },
    
    loadMore() {
      if (this.isLoading || !this.hasMore) return;
      this.currentPage++;
      this.getInvoiceList();
    },
    
    handlePaginationChange(e) {
      this.currentPage = e.currentPage;
      this.getInvoiceList(this.currentPage, true);
    },
    
    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    
    goHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    
    issueInvoice(index) {
      this.selectedInvoiceIndex = index;
      this.selectedInvoice = this.invoiceList[index];
      this.$refs.invoicePopup.open('center');
    },
    
    cancelIssueInvoice() {
      this.$refs.invoicePopup.close();
    },
    
    confirmIssueInvoice() {
      if (!this.selectedInvoice) {
        uni.showToast({ title: '请选择要开票的记录' });
        return;
      }
      
      let params = {
        orderSn: this.selectedInvoice.outTradeNo,
        amount: this.selectedInvoice.totalAmount,
        remark: '停车费'
      }
      
      invoiceIssue(params)
        .then(res => {
          const data = res.data;
          const { urlQRCode } = data;
          uni.navigateTo({
            url: `/pages/parking/web_view/index?url=${encodeURIComponent(urlQRCode)}`,
            success: () => console.log('跳转成功'),
            fail: (err) => console.log('跳转失败原因', err)
          });
        })
        .catch(err => {
          console.error('获取失败:', err);
        });
    },
    
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
  }
}
</script>

<style scoped lang="scss">
.data-list {
  padding: 20rpx;
}

.car-item {
  display: flex;
  align-items: center;
  margin: 0 auto;
  padding: 20rpx 40rpx 20rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  height: 100rpx;
  width: 95%;
}

.car-item.active {
  background-color: #FEF6EF;
  border-color: #FE725C;
}

.icon {
  width: 30rpx;
  height: 30rpx;
  margin-right: 20rpx;
}

.invoice-info {
  flex: 1;
  margin-left: 8rpx;
}

.invoice-date {
  font-size: 28rpx;
  color: #333333;
  display: block;
}

.invoice-fee {
  font-size: 32rpx;
  color: #FE725C;
  font-weight: bold;
  display: block;
  margin-top: 5rpx;
}

.issue-button {
  font-size: 24rpx;
  color: #007AFF;
  border-color: #007AFF;
  background-color: transparent;
  border-width: 2rpx;
  border-style: solid;
  border-radius: 40rpx;
  padding: 0 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 36rpx;
  line-height: 36rpx;
  width: 114rpx;
}

.hint-text {
  font-size: 24rpx;
  color: #999999;
  text-align: center;
  margin-top: 100rpx;
  display: v-bind('invoiceList.length === 0 ? block : none');
}

.pagination-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #f5f5f5;
  padding-bottom: var(--safe-area-inset-bottom);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.popup-content {
  background-color: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  width: 95%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
}

.invoice-detail {
  width: 100%;
  margin: 20rpx 0;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

.detail-item {
  display: flex;
  margin-bottom: 15rpx;
  font-size: 28rpx;
}

.detail-label {
  color: #666;
  width: 120rpx;
}

.detail-value {
  color: #333;
  flex: 1;
}

.popup-buttons {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 40rpx;
}

.popup-button {
  width: 45%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cancel {
  color: #333;
  background-color: #f5f5f5;
}

.confirm {
  color: #ffffff;
  background-color: #007AFF;
}

.keyboard {
  position: fixed;
  bottom: 0;
  background-color: #d1d5d9;
  width: 100%;
  left: 0;
  padding: 10rpx 0;
  z-index: 1000;
  box-sizing: border-box;
}

.keyboardClose {
  height: 70rpx;
  background-color: #f7f7f7;
  overflow: hidden;
  padding: 0 20rpx;
}

.keyboardClose_btn {
  float: right;
  line-height: 70rpx;
  font-size: 15px;
}

.keyboard-line {
  display: flex;
  justify-content: center;
  flex-wrap: nowrap;
  padding: 5rpx 10rpx;
  box-sizing: border-box;
  margin: 0 auto;
  max-width: 750rpx;
}

.keyboard-btn {
  font-size: 32rpx;
  color: #333333;
  background: #fff;
  text-align: center;
  box-shadow: 0 2rpx 0 0 #999999;
  border-radius: 10rpx;
  margin: 5rpx;
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1 0 60rpx;
  max-width: 60rpx;
}

.keyboard-del {
  font-size: 32rpx;
  color: #333333;
  background: #a7b0bc;
  display: inline-block;
  padding: 0;
  box-shadow: 0 2rpx 0 0 #999999;
  border-radius: 10rpx;
  margin: 5rpx;
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  position: absolute;
  bottom: 15rpx;
  right: 15rpx;
}

.new {
  color: #999;
  text-align: center;
  font-size: 36rpx;
  width: 100%;
  vertical-align: top;
}

.load-more, .loading, .no-more {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  padding: 20rpx 0;
}

.load-more {
  cursor: pointer;
  color: #007AFF;
}

.loading {
  color: #999;
}

.no-more {
  color: #ccc;
}
</style>